package com.wlm.Utils;

import com.fasterxml.jackson.databind.ObjectMapper;



import java.io.PrintWriter;
import java.io.StringWriter;


public class Utils {

    private static ObjectMapper mapper = new ObjectMapper();


    public static <T> String obj2JsonStr(T obj) {
        // 方法一：使用JSONObject
        // JsonConfig config = new JsonConfig();
        // config.registerJsonValueProcessor(Date.class, new
        // JsonDateValueProcessor());
        // JSONObject json = JSONObject.fromObject(obj,config);
        // String strContext = json.toString();
        // return strContext;

        // 方法二：使用Jackson
        // ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(obj);
        }
        catch (Exception e) {
//            log.error("Json serialization failed.{}", Utils.getErrorMsg(e));
            return json;
        }
        return json;
    }


    public static String getErrorMsg(Exception e) {
        String errorMsg = null;
        if (e == null) {
            return errorMsg;
        }
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true)) {
            e.printStackTrace(pw);
            return sw.toString();
        }
        catch (Exception e1) {
            return errorMsg;
        }
    }


    /**
     * Description: 将JSON转换成对象<br>
     *
     * @param jsonStr
     *            JSON
     * @param clas
     *            对象的类类型
     * @return 对象<br>
     * @author GC<br>
     */
    public static <T> T jsonStr2Obj(String jsonStr, Class<T> clas) {
        // 方法一：使用JSONObject
        // JSONObject jsonObj = JSONObject.fromObject(jsonStr);
        // //日期转化格式
        // String[] dateFormats = new String[]
        // {DViewConstant.RegularString.DEFAULT_DATE_TIME_FORMAT};
        // JSONUtils.getMorpherRegistry().registerMorpher(new
        // DateMorpherEx(dateFormats,
        // (Date) null));
        // @SuppressWarnings("unchecked")
        // T obj = (T) JSONObject.toBean(jsonObj, clas);
        // return obj;

        // 方法二：使用Jackson
        // ObjectMapper mapper = new ObjectMapper();
        T obj = null;
        try {
            obj = mapper.readValue(jsonStr, clas);
        }
        catch (Exception e) {
//            log.error("Exception to jsonStr2Obj:", e);
            return obj;
        }
        return obj;
    }

}
